<template>
  <view class="container">
    <view class="sign-info" v-if="consecutiveDays > 0">
      <text class="sign-days">已连续签到 <text class="days-count">{{ consecutiveDays }}</text> 天</text>
      <text class="today-points">今日获得+0.1积分</text>
    </view>
    
    <view class="calendar">
      <view class="calendar-header">
        <view class="month-switcher prev" @click="changeMonth(-1)">上月</view>
        <view class="current-month">{{ currentMonth }}</view>
        <view class="month-switcher next" @click="changeMonth(1)">下月</view>
      </view>
      
      <view class="weekdays">
        <view class="weekday" v-for="weekday in weekdays" :key="weekday">{{ weekday }}</view>
      </view>
      
      <view class="days">
        <view class="day" v-for="(day, index) in days" :key="index">
          <view 
            class="day-number" 
            :class="{ 
              active: day.isActive, 
              current: day.isCurrent,
              signed: day.isSigned
            }"
          >
            {{ day.number }}
            <view v-if="day.isSigned" class="signed-mark">✓</view>
          </view>
        </view>
      </view>
    </view>
    
    <view class="sign-button" @click="handleSignIn" :disabled="isAlreadySigned">签到</view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ApiIsSgin, ApiSgin } from '../api/common';

// 日期相关变量
const currentDate = new Date();
const currentYear = ref(currentDate.getFullYear());
const currentMonthIndex = ref(currentDate.getMonth());
const currentDayOfMonth = ref(currentDate.getDate());

// 签到状态相关变量
const consecutiveDays = ref(0);
const signInDate = ref('');
const signInStatus = ref(0);
const continuous = ref(false);

// 日历显示相关变量
const currentMonth = ref(`${currentYear.value}年${currentMonthIndex.value + 1}月`);
const weekdays = ref(['日', '一', '二', '三', '四', '五', '六']);

// 已签到日期和日历数据
const signedDates = reactive([]);
const days = reactive([]);

// 生成日历数据
const generateDays = () => {
  days.length = 0;
  const firstDay = new Date(currentYear.value, currentMonthIndex.value, 1).getDay();
  
  // 上个月的日期
  for (let i = firstDay - 1; i >= 0; i--) {
    const lastMonthDay = new Date(currentYear.value, currentMonthIndex.value, 0).getDate() - i;
    days.push({
      number: lastMonthDay,
      isActive: false,
      isSigned: false,
      isCurrent: false
    });
  }
  
  // 当前月的日期
  const daysInMonth = new Date(currentYear.value, currentMonthIndex.value + 1, 0).getDate();
  for (let i = 1; i <= daysInMonth; i++) {
    const isActive = i === currentDayOfMonth.value && 
                    currentYear.value === currentDate.getFullYear() && 
                    currentMonthIndex.value === currentDate.getMonth();
    let isSigned = false;
    
    // 检查是否已签到
    for (const signedDate of signedDates) {
      if (signedDate.year === currentYear.value && 
          signedDate.month === currentMonthIndex.value && 
          signedDate.day === i) {
        isSigned = true;
        break;
      }
    }
    
    days.push({
      number: i,
      isActive: isActive,
      isSigned: isSigned,
      isCurrent: isActive
    });
  }
};

// 获取签到状态
const getSingStatus = async () => {
  try {
    const res = await ApiIsSgin();
    if (res.signInStatus === 1) {
      signInStatus.value = res.signInStatus;
      consecutiveDays.value = res.consecutiveDays;
      continuous.value = res.continuous;
      signInDate.value = res.signInDate;
      
      // 解析签到日期并添加到signedDates
      const [year, month, day] = res.signInDate.split('-').map(Number);
      signedDates.push({
        year,
        month: month - 1, // 月份从0开始
        day: day
      });
      
      // 存储到本地存储（使用 uni API）
      uni.setStorageSync('signedDates', JSON.stringify(signedDates));
    }
  } catch (error) {
    console.error('获取签到状态失败:', error);
  }
};

// 页面加载时初始化
onMounted(() => {
  // 获取签到状态
  getSingStatus().then(() => {
    generateDays();
  });
  
  // 从本地存储加载已签到日期（使用 uni API）
  const cachedSignedDates = uni.getStorageSync('signedDates');
  if (cachedSignedDates) {
    const parsedDates = JSON.parse(cachedSignedDates);
    parsedDates.forEach(date => {
      signedDates.push(date);
    });
  }
  
  // 生成日历
  generateDays();
});

// 切换月份
const changeMonth = (delta) => {
  currentMonthIndex.value += delta;
  if (currentMonthIndex.value < 0) {
    currentMonthIndex.value = 11;
    currentYear.value--;
  } else if (currentMonthIndex.value > 11) {
    currentMonthIndex.value = 0;
    currentYear.value++;
  }
  currentMonth.value = `${currentYear.value}年${currentMonthIndex.value + 1}月`;
  generateDays();
};

// 计算是否已签到
const isAlreadySigned = computed(() => {
  if (currentYear.value !== currentDate.getFullYear() || 
      currentMonthIndex.value !== currentDate.getMonth()) {
    return false;
  }
  for (const signedDate of signedDates) {
    if (signedDate.year === currentYear.value && 
        signedDate.month === currentMonthIndex.value && 
        signedDate.day === currentDayOfMonth.value) {
      return true;
    }
  }
  return false;
});

// 处理签到
const handleSignIn = async () => {
  if (isAlreadySigned.value) {
    uni.showToast({
      title: '今天已经签到过了！',
      icon: 'none'
    });
    return;
  }
  
  try {
    await ApiSgin();
    // 更新签到状态
    await getSingStatus();
    generateDays();
    
    uni.showToast({
      title: '签到成功！',
      icon: 'none'
    });
    
    // 添加今天到已签到日期
    const today = new Date();
    signedDates.push({
      year: today.getFullYear(),
      month: today.getMonth(),
      day: today.getDate()
    });
    
    // 存储到本地存储（使用 uni API）
    uni.setStorageSync('signedDates', JSON.stringify(signedDates));
  } catch (error) {
    console.error('签到失败:', error);
    uni.showToast({
      title: '签到失败，请稍后再试！',
      icon: 'none'
    });
  }
};
</script>


<style scoped>
body, html {
  overflow: hidden;
}

.container {
  height: 100%;	
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.sign-info {
  background-color: white;
  margin-top: 10px;
  margin-left: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.sign-days {
  font-size: 20px;
  font-weight: bold;
}

.days-count {
  color: #ff9800;
}

.today-points {
  color: #ff9800;
  margin-top: 5px;
  margin-left: 20rpx;
}

.calendar {
  background-color: white;
  margin: 20px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #f9f9f9;
}

.month-switcher {
  color: #999;
  font-size: 14px;
}

.current-month {
  font-size: 16px;
  font-weight: bold;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background-color: #f9f9f9;
  padding: 10px 0;
  text-align: center;
}

.weekday {
  font-size: 14px;
  color: #999;
}

.days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  padding: 10px;
}

.day {
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.day-number {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  font-size: 14px;
  position: relative;
}

.day-number.active {
  background-color: #ff9800;
  color: white;
}

.day-number.current {
  border: 2px solid #ff9800;
}

.signed-mark {
  position: absolute;
  bottom: -5px;
  color: #4CAF50;
  font-weight: bold;
}

.sign-button {
  background-color: #ff9800;
  color: white;
  text-align: center;
  padding: 15px 0;
  border-radius: 25px;
  font-size: 16px;
  margin: 20px;
  box-shadow: 0 2px 10px rgba(255, 152, 0, 0.3);
}

.sign-button:disabled {
  background-color: #ccc;
  color: #666;
}
</style>

